package sg.edu.nus.iss.cats.controller;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import sg.edu.nus.iss.cats.model.*;
import sg.edu.nus.iss.cats.dataaccess.DAOException;

public class ModifyUserRolesServlet extends HttpServlet {

     Role[] allRoles = null;

     public void init(ServletConfig config) throws ServletException {
    
        // Store the ServletConfig object and log the initialization
        super.init(config);

        try {
            //Load the roles from DB
            UserManager userManager = new UserManager();
            allRoles = userManager.findAllRoles();

            //Store in the servletcontext so that other objects can share the role list
            getServletContext().setAttribute("ALLROLES",allRoles);
            
        }catch(DAOException e){
            throw new ServletException("Error loading the roles from DB");
            
        }
        
     }  
     
     
    public void doGet(HttpServletRequest request,HttpServletResponse response)
            throws ServletException, IOException {
            
            doPost(request,response);
            
    }

    public void doPost(HttpServletRequest request,HttpServletResponse response)
            throws ServletException, IOException {
    
        //Check is user logged in
        HttpSession session = request.getSession(true);
        UserSession userSession = (UserSession) session.getAttribute("USERSESSION");

        if (session==null || userSession==null){
             HTMLUtil.displayException(request,response,"Sorry, please login to access this page....");
            return;
        
        }
        
        //Check if user is ADMIN
        if (userSession.isAdmin()){
        
            //By default display the list of users   
            //Get details of all users
            User[] users = null;
            try {
                //Get all users details from DB and display
                UserManager userManager = new UserManager();
                users = userManager.findAllUsers();
            }catch (DAOException e){
                HTMLUtil.displayException(request,response,
                  "Sorry, an error occurred getting the users details");
                return;
            }  
            
                        
            String action = request.getParameter("action");
            
            //default action
            if (action == null || action.equals("")){
                showModifyUsersPage(request,response,users);
                return;
            }

            System.out.println("ModifyRolesServlet : action " + action);
            
            if (action.equals("showuser")){      
            
               showModifyUserForm(request,response,users);
               
            } else if (action.equals("modify")){          
            
                modifyUser(request,response); 
                
            } else {

                showModifyUsersPage(request,response,users);
                
            }
           
            
        }else {
            HTMLUtil.displayException(request,response,        
                        "Sorry, an error occurred getting the users details");
            return;
        }
        
        
        
    }
    
    
    //Get all users details and display in a form to modify
    private void showModifyUsersPage(HttpServletRequest request,  
                 HttpServletResponse response,User[] users) 
                 throws IOException{
      
        
        //Display the user list to modify the roles
        HTMLUtil.displayModifyUserPage(request,response,users);
            
            
    }
    
    
    private void showModifyUserForm(HttpServletRequest request,
                 HttpServletResponse response, User[] users) 
                 throws IOException{
        String userId = request.getParameter("user_id");

        //get the user info from the userlist       
        User user = null;
        for (int i=0;i<users.length;i++){

            if (users[i].getUserId().equals(userId)){
                user = users[i];
                break;
            }
        }
        
        //Display the user list to modify the roles
        HTMLUtil.displayUserForm(request,response,user,this);
    
    }    


    private void modifyUser(HttpServletRequest request,
                 HttpServletResponse response) throws ServletException,IOException{
                 
        User modifiedUser = new User();
        
        
        String userId = request.getParameter("userId");
        String modifiedName = request.getParameter("name");
        String modifiedPassword = request.getParameter("password");
        String modifiedEmployeeId =  request.getParameter("employeeId");
        
        String[] modifiedRoleIds =  request.getParameterValues("roleIds");
        
        if (modifiedName == null || modifiedPassword == null || 
            modifiedEmployeeId == null || modifiedName.equals("") || modifiedPassword.equals("") || modifiedEmployeeId.equals("") || 
            modifiedRoleIds == null || modifiedRoleIds.equals("")){
            
            HTMLUtil.displayException(request,response,"Sorry, the user details could not be updated. \n Please check the name, password, employeedId and roles.....");
            return;
            
        }
        
        modifiedUser.setUserId(userId);
        modifiedUser.setName(modifiedName);
        modifiedUser.setPassword(modifiedPassword);
        modifiedUser.setEmployeeId(modifiedEmployeeId);
        
        modifiedUser.setRoleIds(modifiedRoleIds);
        try{
            UserManager userManager = new UserManager();
            userManager.updateUser (modifiedUser);
            
        }catch(DAOException e){
            HTMLUtil.displayException(request,response,"Sorry, the user details could not be updated. \n Please check the name, password, employeedId and roles.....");
                    return;
                    
        }
       //Forward to page which lists users
       RequestDispatcher rd = getServletContext().getRequestDispatcher( 
               "/modifyUser?action=display");
               
        if (rd != null){
           rd.forward(request,response);
        }
        
    }
}